package com.bible.fire.local;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.Locale;

import com.bible.fire.api.TwoDimensionCode;
import com.bible.fire.util.AndroidUtil;
import com.bible.fire.util.ImageUtil;
import com.bible.fire.util.SystemConstant;
import com.bible.fire.util.TimeUtil;
import com.google.zxing.BarcodeFormat;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.format.DateFormat;
import android.util.Log;
import android.widget.ImageView;
import android.widget.Toast;

public class CameraManager {

	/**
	 * 设置intent属性以调用相机
	 * @return
	 */
	private static Intent getCaptureIntent(){
		Intent intent = new Intent( MediaStore.ACTION_IMAGE_CAPTURE );
		String imgName = TimeUtil.getSerialNoFromTime() + ".jpg";
		Uri imgFileUri = Uri.fromFile(new File(SystemConstant.IMG_PATH_IN_SDCARD,imgName));
    	intent.putExtra(MediaStore.EXTRA_OUTPUT, imgFileUri);
    	AndroidUtil.setAttribute( SystemConstant.CAMERA_IMG_NAME, imgName );
    	return intent;
	}
	
	/**
	 * 从activity中启动相机
	 * @param activity
	 */
	public static void startCameraFromActivity(Activity activity){
		if( !AndroidUtil.isHasSdcard() ){
			Toast.makeText(activity, "没有找到存储目录", Toast.LENGTH_LONG ).show();
			return;
		}		
		activity.startActivityForResult(getCaptureIntent(), SystemConstant.REQUEST_CODE_TAKE_PICTURE );
	}
	
	/**
	 * 从fragment中启动相机
	 * @param fragment
	 */
	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	public static void startCameraFromFragment(Fragment fragment){
		if( !AndroidUtil.isHasSdcard() ){
			Toast.makeText(fragment.getActivity(), "没有找到存储目录", Toast.LENGTH_LONG ).show();
			return;
		}
		fragment.startActivityForResult(getCaptureIntent(), SystemConstant.REQUEST_CODE_TAKE_PICTURE );
		
	}
	
	/**
	 * 拍照之后获取照片路径并显示照片缩略图
	 * @param imageView
	 * @return
	 */
	public static String getImageAfterCamera( ImageView imageView ){
		String imgName = (String)AndroidUtil.getAttribute( SystemConstant.CAMERA_IMG_NAME );
		if( imgName  == null ){
			return "";
		}
		String filepath = SystemConstant.IMG_PATH_IN_SDCARD + imgName;
		Bitmap source = BitmapFactory.decodeFile( filepath );
		//水印并压缩
		source = watermark2codeAndCompress( source, filepath, 30 );
		Bitmap thumbnail = ThumbnailUtils.extractThumbnail(source, imageView.getWidth(), imageView.getHeight());
		//回收以防内存泄漏
		source.recycle();
		imageView.setImageBitmap( thumbnail );
		return imgName;
	}
	
	/**
	 * 水印二维码并压缩图片
	 * @param bitmap
	 * @param filepath
	 * @param quality
	 * @return
	 */
	public static Bitmap watermark2codeAndCompress(Bitmap bitmap, String filepath, int quality ){
		String content = "http://www.vtobank.com";
	    Bitmap watermark = TwoDimensionCode.encodeToBitmap(content, BarcodeFormat.QR_CODE, 250, 250);
	    if( watermark != null ){
		   bitmap = ImageUtil.watermarkBitmap( bitmap , watermark);
	    }
	    FileOutputStream fos = null;
	    try {
		   fos = new FileOutputStream( filepath );
		   bitmap.compress( Bitmap.CompressFormat.JPEG, quality, fos );// 把数据写入文件				   
	    }catch(Exception e) {
			Log.e("bitmap", "save picture error", e);
	    }finally{
		   try {
			   fos.flush();
			   fos.close();
		   }catch(IOException e2){
			   Log.e( "ioexception", "file output error", e2 );
		   }
	    }
	    return  bitmap;
	}
	
	/**@deprecated
	 * 点击拍照按钮时调用
	 * @return
	 */
    public static Intent takePictures(){
    	Activity  activity;    	
    	Intent intent = new Intent( MediaStore.ACTION_IMAGE_CAPTURE ); 
    	// 存储卡可用 将照片存储在 sdcard  
    	/*
        if( AndroidUtil.isHasSdcard() ){
        	String imgName = new DateFormat().format("yyyyMMdd_hhmmss",Calendar.getInstance(Locale.CHINA)) + ".jpg";
        	Uri imgFileUri = Uri.fromFile(new File(SystemConstant.IMG_PATH_IN_SDCARD,imgName));
        	intent.putExtra(MediaStore.EXTRA_OUTPUT, imgFileUri);  
        }       
    	if( activity != null ){
    		activity.startActivityForResult( intent, SystemConstant.REQUEST_CODE_TAKE_PICTURE );
    	}*/	
        return intent;
    }
    
    /**@deprecated
     * 将拍摄的照片保存到SD卡上并将缩略图显示在视图中并返回文件名称
     * @param requestCode
     * @param resultCode
     * @param data
     */
    public static String actionAfterTake( int requestCode, int resultCode, Intent data, ImageView imageView ){ 
    	String imgName = "";
    	if (resultCode == Activity.RESULT_OK) { 
    		if(requestCode == SystemConstant.REQUEST_CODE_TAKE_PICTURE ){//拍照返回  
    			if( data != null && data.hasExtra("data") ){
    				//存储卡可用  
     	           if( AndroidUtil.isHasSdcard() ){
     	        	   imgName = DateFormat.format("yyyyMMdd_hhmmss",Calendar.getInstance(Locale.CHINA)) + ".png";    	        	   
     	        	   Bundle bundle = data.getExtras();
     	        	   Bitmap bitmap = (Bitmap) bundle.get("data");// 获取相机返回的数据，并转换为Bitmap图片格式
     	        	   String content = "http://www.vtobank.com";
 	        		   Bitmap watermark = TwoDimensionCode.encodeToBitmap(content, BarcodeFormat.QR_CODE, 70, 70);
 	        		   if( watermark != null ){
 	        			   bitmap = ImageUtil.watermarkBitmap( bitmap , watermark);
 	        		   }
                        FileOutputStream fos = null;
                        File imgDir = new File(SystemConstant.IMG_PATH_IN_SDCARD);
                        if( !imgDir.exists() ){
                     	   imgDir.mkdirs();
                        }
                        try {
 						   fos = new FileOutputStream( SystemConstant.IMG_PATH_IN_SDCARD + imgName );
 						   bitmap.compress( Bitmap.CompressFormat.PNG, 100, fos );// 把数据写入文件
 						   if( imageView != null ){
 							   imageView.setImageBitmap( bitmap );							   
 						   }
 					   }catch(Exception e) {
 							Log.e("bitmap", "save picture error", e);
 					   }finally{
 						   try {
 							   fos.flush();
 							   fos.close();
 						   }catch(IOException e2){
 							   Log.e( "ioexception", "file output error", e2 );
 						   }
 					   }
     	           }
    			}else{
    			   String filepath = "";
    			   Bitmap source = BitmapFactory.decodeFile(filepath);
    			   Bitmap b = ThumbnailUtils.extractThumbnail(source, 200, 200);
    			   source.recycle();
    			}   	           
    		}
    	}
    	return imgName;
    }
    
}
